package com.chart.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chart.chart.domian.req.UListReq;
import com.chart.chart.domian.resp.UserResp;
import com.chart.chart.domian.vo.UserCoinLogVo;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.domain.entity.ChartCoinPackage;
import com.chart.common.core.domain.entity.SysUser;
import com.chart.common.core.domain.entity.UserCoinLog;
import com.chart.common.utils.SecurityUtils;
import com.chart.system.mapper.UserCoinLogsMapper;
import com.chart.system.service.IChartCoinPackageService;
import com.chart.system.service.ISysUserService;
import com.chart.system.service.IUserCoinLogsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class UserCoinLogsServiceImpl extends ServiceImpl<UserCoinLogsMapper, UserCoinLog> implements IUserCoinLogsService {

    @Autowired
    private UserCoinLogsMapper userCoinLogsMapper;


    @Autowired
    private ISysUserService userService;

    @Autowired
    private IChartCoinPackageService chartCoinPackageService;

    @Override
    public int  addLoginCoins(Long userId) {
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX);

        boolean hasLoggedToday = userCoinLogsMapper.existsByUserIdAndActionAndCreatedAtBetween(userId, "LOGIN", startOfDay, endOfDay);
        if (!hasLoggedToday) {
            UserCoinLog log = new UserCoinLog();
            log.setUserId(userId);
            log.setAction("LOGIN");
            // 定义一个变量来存储 addCoin 的值
            Integer addCoin = 0;
            // 获取 ChartCoinPackage 列表
            List<ChartCoinPackage> list = chartCoinPackageService.list();
            for (ChartCoinPackage chartCoinPackage : list) {
                Integer id = chartCoinPackage.getId();
                // 如果 id 等于 1，则设置 log 的 coins
                if (id == 1) { //id=1为登录
                    addCoin = chartCoinPackage.getAddCoin(); // 获取 add_coin 的值
                    // 设置 log 的 coins 为 add_coin
                    log.setCoins(addCoin);
                    // 找到后即可跳出循环，避免不必要的遍历
                    break;
                }
            }
            log.setCreatedAt(LocalDateTime.now());
            save(log);
            return addCoin; // 返回当前加币数
        }
        return 0; // 如果已经登录过，返回0
    }

    @Override
    public int addInfoCompletionCoins(Long userId) {
        boolean hasCompletedInfo = userCoinLogsMapper.existsByUserIdAndAction(userId, "COMPLETE_INFO");
        if (!hasCompletedInfo) {
            SysUser sysUser = new SysUser();
            sysUser.setHasComplete(1);
            sysUser.setUserId(userId);
            boolean isUpdated = userService.updateById(sysUser);  // 确保 updateById 成功执行
            if (!isUpdated) {
                throw new RuntimeException("更新用户信息失败");
            }

            UserCoinLog log = new UserCoinLog();
            log.setUserId(userId);
            log.setAction("COMPLETE_INFO");
            Integer addCoin = 0;
            List<ChartCoinPackage> list = chartCoinPackageService.list();
            for (ChartCoinPackage chartCoinPackage : list) {
                Integer id = chartCoinPackage.getId();
                if (id == 2) {
                    addCoin = chartCoinPackage.getAddCoin(); // 获取 add_coin 的值
                    log.setCoins(addCoin);
                    break;
                }
            }
            log.setCreatedAt(LocalDateTime.now());
            save(log);
            return addCoin; // 返回当前加币数
        }
        return 0; // 如果已经完成信息，返回0
    }

    @Override
    public int addShareCoins(Long userId) {
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX);
        List<UserCoinLog> shareLogs = userCoinLogsMapper.findByUserIdAndActionAndCreatedAtBetween(
                userId, "SHARE", startOfDay, endOfDay);
        int size = shareLogs.size();
        System.out.println(size);
        if (shareLogs.size() < 3) {
            UserCoinLog log = new UserCoinLog();
            log.setUserId(userId);
            log.setAction("SHARE");
            Integer addCoin = 0;
            List<ChartCoinPackage> list = chartCoinPackageService.list();
            for (ChartCoinPackage chartCoinPackage : list) {
                Integer id = chartCoinPackage.getId();
                if (id == 3) {
                    addCoin = chartCoinPackage.getAddCoin(); // 获取 add_coin 的值
                    log.setCoins(addCoin);
                    break;
                }
            }
            log.setCreatedAt(LocalDateTime.now());
            save(log);
            return addCoin; // 返回当前加币数
        }
        return 0; // 如果已经达到限制，返回0
    }


    /**
     * 绑定微信公众号送币
     *
     * @param userId
     * @return
     */
    @Override
    public int addweChatPublicnumber(Long userId) {
        boolean hasCompletedInfo = userCoinLogsMapper.existsByUserIdAndAction(userId, "WECHAT_PUBLIC_NUMBER");
        if (!hasCompletedInfo) {
            UserCoinLog log = new UserCoinLog();
            log.setUserId(userId);
            log.setAction("" +
                    "BIND");
            Integer addCoin = 0;
            List<ChartCoinPackage> list = chartCoinPackageService.list();
            for (ChartCoinPackage chartCoinPackage : list) {
                Integer id = chartCoinPackage.getId();
                if (id == 2) {
                    addCoin = chartCoinPackage.getAddCoin(); // 获取 add_coin 的值
                    log.setCoins(addCoin);
                    break;
                }
            }
            log.setCreatedAt(LocalDateTime.now());
            save(log);
            return addCoin; // 返回当前加币数
        }
        return 0; // 如果已经完成信息，返回0

    }


    @Override
    public int deductAiCoins(Long userId) {
        int coinsToDeduct = 2; // 扣除的金币数
        // 获取当前用户的总金币数
        Integer currentCoins = userCoinLogsMapper.getTotalCoinsByUserId(userId);
        // 检查用户是否有足够的金币
        if (currentCoins == null || currentCoins < coinsToDeduct) {
            return 0; // 不足够的金币，返回0
        }
        // 扣除金币
        UserCoinLog log = new UserCoinLog();
        log.setUserId(userId);
        log.setAction("DEDUCT_AI");
        log.setCoins(-coinsToDeduct); // 扣除金币数，使用负值表示扣除
        log.setCreatedAt(LocalDateTime.now());
        save(log); // 保存扣币记录

        return coinsToDeduct;
    }

    @Override
    public int deductCasePool(Long userId) {
        int coinsToDeduct = 1; // 扣除的金币数
        // 获取当前用户的总金币数
        Integer currentCoins = userCoinLogsMapper.getTotalCoinsByUserId(userId);
        // 检查用户是否有足够的金币
        if (currentCoins == null || currentCoins < coinsToDeduct) {
            return 0; // 不足够的金币，返回0
        }
        // 扣除金币
        UserCoinLog log = new UserCoinLog();
        log.setUserId(userId);
        log.setAction("DEDUCT_POOL");
        log.setCoins(-coinsToDeduct); // 扣除金币数，使用负值表示扣除
        log.setCreatedAt(LocalDateTime.now());
        save(log); // 保存扣币记录
        return coinsToDeduct;
    }


    @Override
    public void saveBehaviorNo(Long userId) {
        UserCoinLog log = new UserCoinLog();
        log.setUserId(userId);
        log.setBehavior("NO");
        log.setNumber(1);
        log.setAction("default_action");
        log.setCreatedAt(LocalDateTime.now());
        save(log);
    }

    @Override
    public void saveBehaviorYes(Long userId) {
        UserCoinLog log = new UserCoinLog();
        log.setUserId(userId);
        log.setBehavior("YES");
        log.setNumber(1);
        log.setAction("default_action");
        log.setCreatedAt(LocalDateTime.now());
        save(log);
    }

    @Override
    public void saveBehaviorClose(Long userId) {
        UserCoinLog log = new UserCoinLog();
        log.setUserId(userId);
        log.setBehavior("CLOSE");
        log.setNumber(1);
        log.setAction("default_action");
        log.setCreatedAt(LocalDateTime.now());
        save(log);
    }

    @Override
    public Integer getTotalNoByUserId(Long userId) {
        return userCoinLogsMapper.getTotalByBehaviorAndUserId("NO", userId);
    }

    @Override
    public Integer getTotalYesByUserId(Long userId) {
        return userCoinLogsMapper.getTotalByBehaviorAndUserId("YES", userId);
    }

    @Override
    public Integer getTotalCloseByUserId(Long userId) {
        return userCoinLogsMapper.getTotalByBehaviorAndUserId("CLOSE", userId);
    }


    @Override
    public Integer getTotalCoinsByUserId(Long userId) {
        return userCoinLogsMapper.getTotalCoinsByUserId(userId);
    }

    @Override
    public AjaxResult operationPv() {
        Long userId = SecurityUtils.getUserId();
        // Long userId = 2L;
        Long operationTotal = 1L; // 设置要插入的操作总数

        // 调用 Mapper 方法
        userCoinLogsMapper.operationPv(userId, operationTotal);

        return AjaxResult.success("操作记录成功");
    }

    @Override
    public Long operationTotal() {
        //  Long userId = 2L;
        Long userId = SecurityUtils.getUserId();
        Long size = userCoinLogsMapper.operationTotal(userId);
        return size;
    }

    @Override
    public AjaxResult operationUv() {
        String action = "OPERATION";
        // Long userId = 2L;
        Long userId = SecurityUtils.getUserId();
        userCoinLogsMapper.insertOperationUv(userId, action);
        return AjaxResult.success();
    }


    @Override
    public List<UserCoinLog> operationUvTotal() {
        //  Long userId = 3L; // 或者通过 SecurityUtils.getUserId() 获取当前用户ID
        Long userId = SecurityUtils.getUserId();
        // 获取操作记录列表
        List<UserCoinLog> logs = userCoinLogsMapper.operationUvTotal(userId);

        // 返回操作记录列表
        return logs;
    }

    @Override
    public AjaxResult operation() {

        Long userId = SecurityUtils.getUserId();
        //  Long userId = 2L;
        Long operationTotal = 1L; // 设置要插入的操作总数
        // 调用 Mapper 方法
        userCoinLogsMapper.operationPv(userId, operationTotal);

        String action = "OPERATION";
        userCoinLogsMapper.insertOperationUv(userId, action);
        return AjaxResult.success();


    }

    @Override
    public AjaxResult logActivity() {
        Long userId = SecurityUtils.getUserId();
        Long operationTotal = 1L; // 默认的操作数量

        // 记录页面访问（PV）操作
        userCoinLogsMapper.logPageView(userId, operationTotal);

        // 记录独特用户（UV）操作
        String actionType = "OPERATION";
        userCoinLogsMapper.logUniqueVisitor(userId, actionType);

        return AjaxResult.success("PV和UV操作已记录");
    }

    @Override
    public AjaxResult getActivitySummary() {
        //Long userId = SecurityUtils.getUserId();
        // 获取总的页面访问（PV）数量
        Long PV = userCoinLogsMapper.getTotalPageViews();
        // 获取独特用户（UV）数量
        Long UV = userCoinLogsMapper.countUniqueVisitors();
        // 构建返回数据
        HashMap<String, Object> summary = new HashMap<>();
        summary.put("pv", PV);
        summary.put("uv", UV);

        return AjaxResult.success(summary);
    }


    /**
     * 当日智点用尽时，询问用户是否愿意付费
     *
     * @param action
     */
    @Override
    public void saveAnalyzeUsersPay(String action) {
        Long userId = SecurityUtils.getUserId();
        UserCoinLog analyzeUsersPay = new UserCoinLog();
        analyzeUsersPay.setUserId(userId);
        analyzeUsersPay.setAction(action);
        analyzeUsersPay.setCreatedAt(LocalDateTime.now());
        save(analyzeUsersPay);
    }


    @Override
    public List<UserCoinLog> getUserCoinLogsByAction(String action) {
        return userCoinLogsMapper.getUserCoinLogsByAction(action);
    }


    @Override
    public Integer shereUv() {
        Long userId = SecurityUtils.getUserId();
        Integer size = userCoinLogsMapper.shereUv(userId);
        return size;
    }

    /**
     *
     */
    @Override
    public void saveSelfProduce() {
        Long userId = SecurityUtils.getUserId();
        Long selfProduce = 1L; // 默认的操作数量

        // 记录页面访问（PV）操作
        userCoinLogsMapper.saveSelfProduce(userId, selfProduce);

    }


    @Override
    public Integer querySelfProduce() {
        Long userId = SecurityUtils.getUserId();
        Integer size = userCoinLogsMapper.querySelfProduce(userId);
        return size;
    }

    @Override
    public void saveAiSelfProduce() {
        Long userId = SecurityUtils.getUserId();
        Long aiSelfProduce = 1L; // 默认的操作数量

// 记录页面访问（PV）操作
        userCoinLogsMapper.saveAiSelfProduce(userId, aiSelfProduce);

    }


    @Override
    public Integer queryAiSelfProduce() {
        Long userId = SecurityUtils.getUserId();
        Integer size = userCoinLogsMapper.queryAiSelfProduce(userId);
        return size;
    }

    @Override
    public void expertSave(Long configsUserId) {
        Long userId = SecurityUtils.getUserId();
        Integer save = 1;
        userCoinLogsMapper.expertSave(userId, configsUserId, save);
    }


    @Override
    public void expertSaveExport(Long configsUserId) {
        Long userId = SecurityUtils.getUserId();
        Integer export = 1;
        userCoinLogsMapper.expertSaveExport(userId, configsUserId, export);
    }

//    @Override
//    public List<UserCoinLog> queryExpertSavePv() {
//        List<UserCoinLog> userCoinLogs = userCoinLogsMapper.queryExpertSavePv();
//        return userCoinLogs;
//    }


    @Override
    public Integer queryExpertSaveUv() {
        Integer saveUv = userCoinLogsMapper.queryExpertSaveUv();
        return saveUv;
    }

    @Override
    public Integer queryExpertSaveUvs() {
        Integer exportUv = userCoinLogsMapper.queryExpertSaveUvs();
        return exportUv;
    }

    @Override
    public List<Map<String, Object>> queryExpertSaveExportUV() {
        return userCoinLogsMapper.queryExpertSaveExportUV();
    }


    @Override
    public void saveAiSave() {
        Long userId = SecurityUtils.getUserId();
        Long aiSave = 1L; // 默认的操作数量
        // 记录页面访问（PV）操作
        userCoinLogsMapper.saveAiSave(userId, aiSave);
    }

    @Override
    public Integer queryAiSave() {
        Long userId = SecurityUtils.getUserId();
        Integer size = userCoinLogsMapper.queryAiSave(userId);
        return size;
    }

    /**
     * 查询席位数量
     *
     * @param seatCount
     * @return
     */
    public int querySeatCount() {
        Long userId = SecurityUtils.getUserId();
        Integer seatCountNumber = userCoinLogsMapper.querySeatCount(userId); // 使用 Integer

        // 如果 seatCountNumber 为 null，返回 0
        if (seatCountNumber == null) {
            return 0;
        }

        return seatCountNumber;
    }


    /**
     * 转发剩余次数
     *
     * @param userId
     * @return
     */
    @Override
    public int residueTime(Long userId) {

        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX);

        List<UserCoinLog> shareLogs = userCoinLogsMapper.findByUserIdAndActionAndCreatedAtBetween(
                userId, "SHARE", startOfDay, endOfDay);

        int size = shareLogs.size();
        int sizeNumber = 3 - size;

        return sizeNumber;
    }

    @Override
    public Map<String, Object> queryExpertSaveExportStats() throws ParseException {


        // Retrieve the PV data
        List<UserCoinLog> pvData = userCoinLogsMapper.queryExpertSavePv();

        // Retrieve the UV data
        List<Map<String, Object>> uvData = userCoinLogsMapper.queryExpertSaveExportUV();

        // Map to hold PV data by configsUserId (as Long)
        Map<Long, UserCoinLog> pvDataMap = new HashMap<>();
        for (UserCoinLog log : pvData) {
            pvDataMap.put(log.getConfigsUserId(), log);
        }

        // Update UV data with PV data
        for (Map<String, Object> uvEntry : uvData) {
            Long configsUserId = (Long) uvEntry.get("configsUserId");
            UserCoinLog pvEntry = pvDataMap.get(configsUserId);

            if (pvEntry != null) {
                uvEntry.put("save", pvEntry.getSave());
                uvEntry.put("export", pvEntry.getExport());
            } else {
                uvEntry.put("save", 0);
                uvEntry.put("export", 0);
            }
        }

        // Return the result with only the updated UV data
        Map<String, Object> result = new HashMap<>();
        result.put("msg", "操作成功");
        result.put("code", 200);
        result.put("data", uvData);
        return result;
    }

    @Override
    public List<UserCoinLogVo> getChartData(UListReq req) {
        return userCoinLogsMapper.getChartData(req);
    }


    /**
     * 总登录次数、月登录次数、
     * 付费用户标识（包括vip/智点购买）
     *
     * @return
     */
    @Override
    public List<UserResp> querydemo() {
        List<UserResp> list = userCoinLogsMapper.querydemo();
        return list;
    }

    /**
     * 用户扣币行为查询
     *
     * @return
     */
    @Override
    public List<UserCoinLog> queryAction(UListReq req) {
        String phoneNumber = req.getPhoneNumber();
        String action = req.getAction();
        String startTime = req.getStartTime();
        String endTime = req.getEndTime();
        List<UserCoinLog> userCoinLogList = userCoinLogsMapper.queryAction(phoneNumber, action, startTime, endTime);
        return userCoinLogList;
    }

    @Override
    public List<UserCoinLogVo> queryExpertSaveExports(UListReq req) {

        List<UserCoinLogVo> chartDataList = userCoinLogsMapper.queryExpertSaveExports(req);
        return chartDataList;
    }


}
